<!DOCTYPE html>






<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">







  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">



















































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="编程语言,">










<meta name="description" content="1234567891011121314151617// 方式1view.setOnClickListener(new View.OnClickListener() &amp;#123;    @Override    public void onClick(View v) &amp;#123;        System.out.println(&quot;I am clicked&quot;);    &amp;#125;&amp;#125;);">
<meta name="keywords" content="编程语言">
<meta property="og:type" content="article">
<meta property="og:title" content="函数式编程的理解(Java语言)">
<meta property="og:url" content="https://zachaxy.github.io/2019/09/07/introduce-Java8-lambda/index.html">
<meta property="og:site_name" content="zachaxy">
<meta property="og:description" content="1234567891011121314151617// 方式1view.setOnClickListener(new View.OnClickListener() &amp;#123;    @Override    public void onClick(View v) &amp;#123;        System.out.println(&quot;I am clicked&quot;);    &amp;#125;&amp;#125;);">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-09-15T05:04:54.437Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="函数式编程的理解(Java语言)">
<meta name="twitter:description" content="1234567891011121314151617// 方式1view.setOnClickListener(new View.OnClickListener() &amp;#123;    @Override    public void onClick(View v) &amp;#123;        System.out.println(&quot;I am clicked&quot;);    &amp;#125;&amp;#125;);">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zachaxy.github.io/2019/09/07/introduce-Java8-lambda/">





  <title>函数式编程的理解(Java语言) | zachaxy</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">






  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zachaxy</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <h1 class="site-subtitle" itemprop="description">纵情向前！</h1>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>

            归档
          </a>
        </li>


        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">

              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>

            关于
          </a>
        </li>



        <li class="menu-item menu-item-search">

            <a href="javascript:;" class="popup-trigger">


              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>

            搜索
          </a>
        </li>

    </ul>



    <div class="site-search">

  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>

</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">


  <div id="posts" class="posts-expand">








  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2019/09/07/introduce-Java8-lambda/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">函数式编程的理解(Java语言)</h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-09-07T09:53:38+08:00">
                2019-09-07
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  3,941
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">





        <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 方式1</span></span><br><span class="line">view.setOnClickListener(<span class="keyword">new</span> View.OnClickListener() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onClick</span><span class="params">(View v)</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"I am clicked"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 方式2</span></span><br><span class="line">view.setOnClickListener(v -&gt; System.out.println(<span class="string">"I am clicked"</span>));</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方式3</span></span><br><span class="line">view.setOnClickListener(<span class="keyword">this</span>::onViewClick);</span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">onViewClick</span><span class="params">(View view)</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">"I am clicked"</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面三种方式最终都是为view 设置了点击的监听,最终效果都是一样的, 但是哪种方式更好呢?</p>
<a id="more"></a>
<h1 id="几个基本的概念"><a href="#几个基本的概念" class="headerlink" title="几个基本的概念"></a>几个基本的概念</h1><ul>
<li><p>函数式接口(Functional Interface): 有且仅有一个抽象方法，但是可以有多个非抽象方法的接口。</p>
</li>
<li><p>函数式编程(functional programming),也称函数程序设计，或者泛函编程: 是一种编程典范，它将电脑运算视为数学上的函数计算，并且避免使用程序状态以及易变对象。其实,函数式并非是 Java8 首创的概念,其本身是范畴论（Category Theory）的数学分支,用来解决数学问题的,后来有人将这种方法论运用在了编程上,所以才形成了函数式编程</p>
</li>
<li><p>函数编程语言最重要的基础是λ演算(lambda calculus)。而且λ演算的函数可以接受函数当作输入（引数）和输出（传出值）。比起指令式编程，函数式编程更加强调程序执行的结果而非执行的过程，倡导利用若干简单的执行单元让计算结果不断渐进，逐层推导复杂的运算，而不是设计一个复杂的执行过程。</p>
</li>
<li><p>Lambda表达式: Lambda允许把函数作为一个方法的参数(函数作为参数传递进方法中)</p>
</li>
<li><p>方法引用: lambda表达式的一种特殊形式，如果正好有某个方法满足一个lambda表达式的形式，那就可以将这个lambda表达式用方法引用的方式表示，但是如果这个lambda表达式的比较复杂就不能用方法引用进行替换。实际上方法引用是lambda表达式的一种语法糖。</p>
</li>
</ul>
<hr>
<p>上述几个概念似乎没有什么关联,那么我们再次回到文章开头给出的三种实现方式. 第一种方式是最常见的一种方式,view 的 setOnClickListener 方法要传入一个接口, 我们一般都是直接在参数传入的地方,传入一个匿名内部类,但是这样使得代码的整体结构变得略微有些复杂,并且不够直观,那么有没有一种更简洁的写法呢? 于是 Java8 便退出了更为简洁的lambda 表达式,一行代码就可以替代之前臃肿的结构.</p>
<p>但是,并非所有参数是接口的方法,都可以用 lambda 表达式来替代,这个接口有一个特殊的限定—有且仅包含一个抽象方法的接口(函数式接口). Java8 并没有在之前的基础上提供额外的语法来创建函数式接口,而是在原有接口的范畴内,进行限定.这样就可以在参数为函数式接口的方法中,使用 lambda 来表达.</p>
<p>透过开篇的示例代码,我们发现 setOnClickListener 方法要传入一个接口,本质上是在view 接受到点击事件后,要往外抛出一个事件,而接口正是 view 内部点击事件与外部处理点击事件的桥梁,实际上,就是需要一个特定的代码块来处理点击事件,所以lambda表达式就产生了,但是如果我们再进一步分析,似乎我们并没有必要特意去强调实现了该接口,才可以接受回调,只要满足其接口内的方法签名,任意一个方法都可以传入用来处理对应的回调,甚至都不需要满足函数式接口的约束,这就是方法引用产生的背景.</p>
<p>方法引用提供了非常有用的语法，可以直接引用已有Java类或对象（实例）的方法或构造器。与lambda联合使用，方法引用可以使语言的构造更紧凑简洁，减少冗余代码。</p>
<h1 id="Lambda-简介"><a href="#Lambda-简介" class="headerlink" title="Lambda 简介"></a>Lambda 简介</h1><p>Lambda 表达式，也可称为闭包,其替代的是函数式接口被当做参数传入方法是的一种场景.</p>
<p>Lambda 表达式的语法格式如下(两种方式):</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">(parameters) -&gt; expression</span><br><span class="line"></span><br><span class="line">(parameters) -&gt;&#123; statements; &#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>可选类型声明：不需要声明参数类型，编译器可以统一识别参数值。</li>
<li>可选的参数圆括号：一个参数无需定义圆括号，但多个参数需要定义圆括号。</li>
<li>可选的大括号：如果主体包含了一个语句，就不需要使用大括号。</li>
<li>可选的返回关键字：如果主体只有一个表达式返回值则编译器会自动返回值. 如果使用大括号,则需要指定明表达式返回了一个数值。</li>
</ul>
<p>lambda 表达式实例</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 1. 不需要参数,返回值为 5  </span></span><br><span class="line">() -&gt; <span class="number">1</span>  </span><br><span class="line">  </span><br><span class="line"><span class="comment">// 2. 接收一个参数(数字类型),返回其2倍的值  </span></span><br><span class="line">x -&gt; <span class="number">2</span> * x  </span><br><span class="line">  </span><br><span class="line"><span class="comment">// 3. 接受2个参数(数字),并返回他们的和</span></span><br><span class="line">(x, y) -&gt; x + y  </span><br><span class="line">  </span><br><span class="line"><span class="comment">// 4. 接收2个int型整数,返回他们的和  </span></span><br><span class="line">(<span class="keyword">int</span> x, <span class="keyword">int</span> y) -&gt; x + y  </span><br><span class="line">  </span><br><span class="line"><span class="comment">// 5. 接受一个 string 对象,并在控制台打印,不返回任何值</span></span><br><span class="line">(String s) -&gt; System.out.print(s)</span><br></pre></td></tr></table></figure>

<p><strong>再次重申</strong>:单纯的定义lambda表达式,没有任何意义, lambda 表达式只有在传入函数式接口为参数的方法被调用时,才可以替代为lambda表达式</p>
<h1 id="函数式编程的核心思想"><a href="#函数式编程的核心思想" class="headerlink" title="函数式编程的核心思想"></a>函数式编程的核心思想</h1><p>最主要的特征是，函数是第一等公民。强调将计算过程分解成可复用的函数只有引用透明的、没有副作用的函数,才是合格的函数.</p>
<p>这里有三个特性需要特别说明:</p>
<ul>
<li><p>函数是”第一等公民”: 所谓”第一等公民”（first class），指的是函数与其他数据类型一样，处于平等地位，它不仅拥有一切传统函数的使用方式（声明和调用），可以赋值给其他变量（赋值），也可以作为参数，传入另一个函数（传参），或者作为别的函数的返回值（返回）。函数可以作为参数进行传递，意味我们可以把行为”参数化”，处理逻辑可以从外部传入，这样程序就可以设计得更灵活。</p>
</li>
<li><p>引用透明（Referential transparency），指的是函数的运行不依赖于外部变量或”状态”，只依赖于输入的参数，任何时候只要参数相同，引用函数所得到的返回值总是相同的。这里强调了一点”输入”不变则”输出”也不变，就像数学函数里面的f(x),只要输入的x一样那得到的结果也肯定定是一样的。</p>
</li>
<li><p>所谓”副作用”（side effect），指的是函数内部与外部互动（最典型的情况，就是修改全局变量的值），产生运算以外的其他结果。函数式编程强调没有”副作用”，意味着函数要保持独立，所有功能就是返回一个新的值，没有其他行为，尤其是不得修改外部变量的值。</p>
</li>
</ul>
<p>根据函数式编程的特性,我们发现函数式编程有以下天然的优势:</p>
<ol>
<li><p>代码简洁，开发快速。</p>
<blockquote>
<p>函数式编程大量使用函数，减少了代码的重复，因此程序比较短，开发速度较快。Paul Graham在《黑客与画家》一书中写道：同样功能的程序，极端情况下，Lisp代码的长度可能是C代码的二十分之一。如果程序员每天所写的代码行数基本相同，这就意味着，”C语言需要一年时间完成开发某个功能，Lisp语言只需要不到三星期。反过来说，如果某个新功能，Lisp语言完成开发需要三个月，C语言需要写五年。”当然，这样的对比故意夸大了差异，但是”在一个高度竞争的市场中，即使开发速度只相差两三倍，也足以使得你永远处在落后的位置。” </p>
</blockquote>
</li>
<li><p>接近自然语言，易于理解</p>
<blockquote>
<p>函数式编程的自由度很高，可以写出很接近自然语言的代码。这基本就是自然语言的表达了，大家应该一眼就能明白它的意思吧。 </p>
</blockquote>
</li>
<li><p>更方便的代码管理</p>
<blockquote>
<p>函数式编程不依赖、也不会改变外界的状态，只要给定输入参数，返回的结果必定相同。因此，每一个函数都可以被看做独立单元，很有利于进行单元测试（unit testing）和除错（debugging），以及模块化组合。 </p>
</blockquote>
</li>
<li><p>易于”并发编程”</p>
<blockquote>
<p>函数式编程不需要考虑”死锁”（deadlock），因为它不修改变量，所以根本不存在”锁”线程的问题。不必担心一个线程的数据，被另一个线程修改，所以可以很放心地把工作分摊到多个线程，部署”并发编程”（concurrency）。请看下面的代码：</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">var s1 = f1();</span><br><span class="line">var s2 = f2();</span><br><span class="line">var s3 = concat(f1, f2);</span><br></pre></td></tr></table></figure>

</li>
</ol>
<blockquote>
<p>由于s1和s2互不干扰，不会修改变量，谁先执行是无所谓的，所以可以放心地增加线程，把它们分配在两个线程上完成。其他类型的语言就做不到这一点，因为s1可能会修改系统状态，而s2可能会用到这些状态，所以必须保证s2在s1之后运行，自然也就不能部署到其他线程上了。多核CPU是将来的潮流，所以函数式编程的这个特性非常重要。</p>
</blockquote>
<ol start="5">
<li>代码的热升级<blockquote>
<p>函数式编程没有副作用，只要保证接口不变，内部实现是外部无关的。所以，可以在运行状态下直接升级代码，不需要重启，也不需要停机。Erlang语言早就证明了这一点，它是瑞典爱立信公司为了管理电话系统而开发的，电话系统的升级当然是不能停机的。</p>
</blockquote>
</li>
</ol>
<h1 id="best-practice"><a href="#best-practice" class="headerlink" title="best practice"></a>best practice</h1><ol>
<li><p>Lambda表达式的底层实现</p>
<blockquote>
<p>Java8 内部 Lambda 表达式的实现方式在本质是以匿名内部类的形式的实现的,但是注意, <strong>lambda 和 匿名内部类并不是等价的</strong>,这里面有个重要的上下文的概念是不同的,也就是<strong>this</strong>的指代,匿名内部类中的 this 就是其内部类对象,而 lambda 中的 this 指的是外部定义该 lambda 的对象,当然如果是定义在静态方法中的 lambda 是无法使用 this 的</p>
</blockquote>
</li>
<li><p>lambda 中使用变量的作用域</p>
</li>
</ol>
<ul>
<li>和匿名内部类相似, 不能在 lambda 内部修改定义在域外的局部变量，否则会编译错误。 </li>
<li>lambda 表达式的局部变量可以不用声明为 final，但是必须不可被后面的代码修改(即隐性的具有 final 的语义),但是依然强烈建议标记为 final,用来表达更明确的语义</li>
<li>在 Lambda 表达式当中不允许声明一个与局部变量同名的参数或者局部变量。</li>
</ul>
<ol start="3">
<li>使用 <code>@FunctionalInterface</code> 注解<blockquote>
<p>如果你确定了某个interface是用于Lambda表达式，请一定要加上@FunctionalInterface，表明你的意图。不然将来说不定某个不知情的同事，在这个interface上面加了另外一个抽像方法时，那么你之前的代码就无法正常运行. 其实 Java8 中已经提供了一些默认的函数式接口供外部使用; 优先使用java.util.function包下面的函数式接口 java.util.function 这个包下面提供了大量的功能性接口，可以满足大多数开发人员为 lambda 表达式和方法引用提供目标类型的需求。每个接口都是通用的和抽象的，使它们易于适应几乎任何lambda表达式。开发人员应该在创建新的功能接口之前研究这个包，避免重复定义接口。另外一点就是，里面的接口不会被别人修改;</p>
</blockquote>
</li>
</ol>
<table>
<thead>
<tr>
<th>函数式接口</th>
<th align="center">参数类型</th>
<th align="center">返回类型</th>
<th align="center">用途</th>
</tr>
</thead>
<tbody><tr>
<td>Consumer<t>(消费型接口)</t></td>
<td align="center">T</td>
<td align="center">void</td>
<td align="center">对类型为T的对象应用操作。void accept(T t)</td>
</tr>
<tr>
<td>Supplier<t>(供给型接口)</t></td>
<td align="center">无</td>
<td align="center">T</td>
<td align="center">返回类型为T的对象。 T get();</td>
</tr>
<tr>
<td>Function&lt;T, R&gt;(函数型接口)</td>
<td align="center">T</td>
<td align="center">R</td>
<td align="center">对类型为T的对象应用操作并返回R类型的对象。R apply(T t);</td>
</tr>
<tr>
<td>Predicate<t>(断言型接口)</t></td>
<td align="center">T</td>
<td align="center">boolean</td>
<td align="center">确定类型为T的对象是否满足约束。boolean test(T t);</td>
</tr>
</tbody></table>
<ol start="4">
<li><p>不要在Lambda表达中执行有”副作用”的操作</p>
<blockquote>
<p>“副作用”是严重违背函数式编程的设计原则，在工作中我经常看到有人在forEach操作里面操作外面的某个List或者设置某个Map这其实是不对的</p>
</blockquote>
</li>
<li><p>尽量避免在lambda中使用{},也就是说lambda的结构体应该尽量简单,如果内部语句复杂,最好定义一个方法,然后在 lambda 结构体中去引用.</p>
</li>
<li><p>相比于lambda,更推荐使用方法引用,虽然两者能起到相同的作用，但两者相比，方法引用通常可读性更高并且代码会简短</p>
</li>
</ol>
<p>方法引用共分为四类:</p>
<ul>
<li>类名::静态方法名</li>
<li>对象::实例方法名</li>
<li>类名::实例方法名(相比于2,其表达含义更清楚,但是这种方式语义的理解有点绕)</li>
<li>类名::new</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Main</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        Student student1 = <span class="keyword">new</span> Student(<span class="string">"aa"</span>, <span class="number">60</span>);</span><br><span class="line">        Student student2 = <span class="keyword">new</span> Student(<span class="string">"bb"</span>, <span class="number">70</span>);</span><br><span class="line">        Student student3 = <span class="keyword">new</span> Student(<span class="string">"cc"</span>, <span class="number">80</span>);</span><br><span class="line">        Student student4 = <span class="keyword">new</span> Student(<span class="string">"dd"</span>, <span class="number">90</span>);</span><br><span class="line">        List&lt;Student&gt; students = Arrays.asList(student1, student2, student3, student4);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        students.sort(<span class="keyword">new</span> Comparator&lt;Student&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">compare</span><span class="params">(Student o1, Student o2)</span> </span>&#123;</span><br><span class="line">                <span class="keyword">return</span> o1.age - o2.age;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        students.sort((o1, o2) -&gt; o1.age - o2.age);</span><br><span class="line"></span><br><span class="line">        students.sort(Main::compare1);</span><br><span class="line"></span><br><span class="line">        students.sort(Student::compare2);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">compare1</span><span class="params">(Student o1, Student o2)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> o1.age - o2.age;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Student</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    String name;</span><br><span class="line">    <span class="keyword">int</span> age;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Student</span><span class="params">(String name, <span class="keyword">int</span> age)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.name = name;</span><br><span class="line">        <span class="keyword">this</span>.age = age;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">compare2</span><span class="params">(Student other)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.age - other.age;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>不要盲目的开启并行流</p>
<blockquote>
<p>Lambda的并行流虽好，但也要注意使用场景。如果平常的业务处理比如过滤，提取数据，没有涉及特别大的数据和耗时操作，则不需要开启并行流。如果一个只有几十个元素的列表的过滤操作也开启了并行流，其实这样做会更慢。因为多行线程的开启和同步这些花费的时间往往比你真实的处理时间要多很多。但一些耗时的操作比如I/O访问，DB查询，远程调用，这些如果可以并行的话，则开启并行流是可提升很大性能的。因为并行流的底层原理是fork/join，如果你的数据分块不是很好切分，也不建议开启并行流。举个例子ArrayList的Stream可以开启并行流，而LinkedList则不建议，因为LinkedList每次做数据切分要遍历整个链表，这本身就已经很浪费性能，而ArrayList则不会</p>
</blockquote>
<h1 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h1><ul>
<li><a href="https://www.cnblogs.com/linlinismine/p/9283532.html" target="_blank" rel="noopener">聊聊Java 8 Lambda 表达式</a></li>
<li><a href="http://www.ruanyifeng.com/blog/2017/02/fp-tutorial.html" target="_blank" rel="noopener">函数式编程入门教程</a></li>
<li><a href="https://segmentfault.com/a/1190000012269548" target="_blank" rel="noopener">Java8-8-方法引用详解</a></li>
</ul>


    </div>









      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zachaxy
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zachaxy.github.io/2019/09/07/introduce-Java8-lambda/" title="函数式编程的理解(Java语言)">https://zachaxy.github.io/2019/09/07/introduce-Java8-lambda/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>


    <footer class="post-footer">

        <div class="post-tags">

            <a href="/tags/编程语言/" rel="tag"># 编程语言</a>

        </div>







        <div class="post-nav">
          <div class="post-nav-next post-nav-item">

              <a href="/2018/04/20/uml图基础/" rel="next" title="uml图基础">
                <i class="fa fa-chevron-left"></i> uml图基础
              </a>

          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">

              <a href="/2019/09/07/how-to-use-curl/" rel="prev" title="curl 使用指南">
                curl 使用指南 <i class="fa fa-chevron-right"></i>
              </a>

          </div>
        </div>




    </footer>
  </div>



  </article>



    <div class="post-spread">

    </div>
  </div>


          </div>









        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

      <div id="sidebar-dimmer"></div>

    <div class="sidebar-inner">




        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>


      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="zachaxy">

              <p class="site-author-name" itemprop="name">zachaxy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives">

                  <span class="site-state-item-count">64</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zachaxy" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>

                <span class="links-of-author-item">
                  <a href="https://weibo.com/3242765540" target="_blank" title="Weibo">

                      <i class="fa fa-fw fa-globe"></i>Weibo</a>
                </span>


          </div>









        </div>
      </section>


      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">






              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#几个基本的概念"><span class="nav-number">1.</span> <span class="nav-text">几个基本的概念</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Lambda-简介"><span class="nav-number">2.</span> <span class="nav-text">Lambda 简介</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#函数式编程的核心思想"><span class="nav-number">3.</span> <span class="nav-text">函数式编程的核心思想</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#best-practice"><span class="nav-number">4.</span> <span class="nav-text">best practice</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#参考"><span class="nav-number">5.</span> <span class="nav-text">参考</span></a></li></ol></div>


          </div>
        </section>
      <!--/noindex-->




    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zachaxy</span>


    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>

      <span class="post-meta-item-text">站点文章字数总计&#58;</span>

    <span title="站点文章字数总计">147.9k</span>

</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>













      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

          <span id="scrollpercent"><span>0</span>%</span>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>







  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>






  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>







































  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>

















  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>





</body>
</html>
